package archive

import (
	"archive/tar"
	"io"
)

var Tar = &archiveTar{}

type archiveTar struct{}

func (receiver *archiveTar) Writer(writer io.Writer, files []File) error {
	tarWriter := tar.NewWriter(writer)

	for _, file := range files {
		tarHeader := &tar.Header{
			Name: file.Name,
			Mode: 0600,
			Size: int64(len(file.Body)),
		}
		if err := tarWriter.WriteHeader(tarHeader); err != nil {
			return err
		}

		if _, err := tarWriter.Write([]byte(file.Body)); err != nil {
			return err
		}
	}

	if err := tarWriter.Close(); err != nil {
		return err
	}

	return nil
}
func (receiver *archiveTar) Reader(reader io.Reader) ([]File, error) {
	tarReader := tar.NewReader(reader)

	var files []File

	for {
		hdr, err := tarReader.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}

		var file File

		file.Name = hdr.Name
		var body []byte
		length, err := tarReader.Read(body)
		if err != nil {
			return nil, err
		}
		file.Body = string(body)
		file.Length = length

		files = append(files, file)
	}

	return files, nil
}
